/*
 * @Description:用户
 * @Author: maskMan
 * @LastEditTime: 2024-11-20 18:37:05
 */
import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators';
import { getManageRoles, login, logOut } from '@/api/login';
import { setItem, setToken, getToken, removeToken } from '@/utils/cookies';
import store from '@/store';
export interface IManagerState {
  token: string;
  managerData: TManager.Info;
  roles: TRole.RoleStruct;
}
@Module({ dynamic: true, store, name: 'manager' })
class Manager extends VuexModule implements IManagerState {
  public token = getToken() || '';
  public managerData: TManager.Info = null;
  public roles: TRole.RoleStruct = null;
  //设置TOKEN
  @Mutation
  set_token(token: string) {
    this.token = token;
  }
  //设置用户数据
  @Mutation
  set_managerData(managerData: TManager.Info) {
    this.managerData = managerData;
  }
  //设置用户角色权限
  @Mutation
  set_roles(roles) {
    this.roles = roles;
  }
  //用户登录
  @Action
  public async Login(userInfo: { username: string; password: string }) {
    let { username, password } = userInfo;
    username = username.trim();
    const ret = await login({ account: username, password });
    if (ret?.status) {
      this.set_token(ret.token);
      setToken(ret.token);
      const account = ret.data?.account;
      setItem('account', account || '');
      return Promise.resolve(ret);
    }
    return Promise.resolve(ret);
  }
  @Action
  public ResetToken() {
    removeToken();
    this.set_token('');
    this.set_managerData(null);
    this.set_roles(null);
  }
  //获取用户权限
  @Action
  public async GetManagerRoles(): Promise<boolean> {
    if (this.token === '') {
      return Promise.resolve(null);
    }
    const ret = await getManageRoles();
    if (ret?.status && ret?.data) {
      this.set_roles(ret.data.roles);
      this.set_managerData(ret.data.manager);
      return Promise.resolve(true);
    }
    return Promise.resolve(null);
  }
  //退出登录
  @Action
  public async LogOut() {
    const ret = await logOut();
    this.ResetToken();
    return Promise.resolve(ret);
  }
}
export const ManagerModule = getModule(Manager);
